<template>
  <div>
    <div style="margin-bottom: 16px;">
      <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddRow">添加物料</el-button>
      <el-button style="margin-left:8px" type="success" size="mini" icon="el-icon-search" @click="openInventorySelector">获取库存</el-button>
    </div>
    <el-table ref="detailTable" :data="value" style="width: 100%" highlight-current-row @current-change="handleCurrentRowChange">
      <el-table-column prop="materialCode" label="料号" width="120" align="center" />
      <el-table-column prop="materialName" label="物料名称" width="120" align="center" />
      <el-table-column prop="materialSpec" label="物料规格" width="120" align="center" />
      <el-table-column prop="unit" label="单位" width="80" align="center" />
      <el-table-column prop="attribute" label="属性" width="100" align="center" />
      <el-table-column prop="batchNumber" label="批号" width="100" align="center" />
      <el-table-column prop="warehouse" label="仓库" width="100" align="center" />
      <el-table-column prop="location" label="库位" width="100" align="center" />
      <el-table-column prop="requiredQuantity" label="需求数量" width="100" align="center" />
              <el-table-column prop="actualQuantity" label="实际领料" width="100" align="center" />
      <el-table-column prop="stockQuantity" label="库存数量" width="100" align="center">
        <template slot-scope="scope">
          <span :class="{ 'insufficient-stock': isInsufficientStock(scope.row) }">
            {{ scope.row.stockQuantity || 0 }}
          </span>
          <el-tag v-if="isInsufficientStock(scope.row)" size="mini" type="danger" style="margin-left: 5px;">
            库存不足
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sourceDocument" label="来源单据" width="120" align="center" />
      <el-table-column prop="sourceOrder" label="来源订单" width="120" align="center" />
      <el-table-column prop="remark" label="备注" width="120" align="center" />
      <el-table-column label="操作" width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row, scope.$index)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.$index)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="选择库存" :visible.sync="inventoryDialogVisible" width="900px" append-to-body>
      <div style="margin-bottom: 16px;">
        <el-button type="primary" size="mini" icon="el-icon-refresh" @click="refreshInventoryList">
          刷新库存列表
        </el-button>
        <el-button type="info" size="mini" icon="el-icon-info" style="margin-left: 8px;" @click="showSelectionHelp">
          选择说明
        </el-button>
        <el-button type="warning" size="mini" icon="el-icon-view" style="margin-left: 8px;" @click="debugSelectionState">
          调试选择状态
        </el-button>
      </div>
      
      <inventory ref="inventoryRef" :selectable="true" @row-click="onInventoryRowClick" @selected-change="onInventoryRowClick" />
      
      <div style="margin-top: 16px; padding: 12px; background-color: #f5f7fa; border-radius: 4px;">
        <div v-if="selectedInventoryRow">
          <strong>已选择库存：</strong>
          <el-tag type="success" size="small" style="margin-left: 8px;">
            {{ selectedInventoryRow.material && selectedInventoryRow.material.materialName || '未知物料' }}
          </el-tag>
          <el-tag type="info" size="small" style="margin-left: 8px;">
            {{ selectedInventoryRow.warehouse && selectedInventoryRow.warehouse.name || '未知仓库' }}
          </el-tag>
          <el-tag type="warning" size="small" style="margin-left: 8px;">
            库存: {{ selectedInventoryRow.quantity || 0 }}
          </el-tag>
        </div>
        <div v-else style="color: #909399;">
          <i class="el-icon-info"></i> 请点击上方表格中的一行来选择库存
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="inventoryDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="applySelectedInventory" :disabled="!selectedInventoryRow">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory } from '@/api/storage/inventory'

export default {
  name: 'PickingDetailTable',
  components: { inventory: () => import('@/views/storage/inventory/index.vue') },
  props: {
    value: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    // 监听父组件传递的数据变化
    value: {
      handler(newVal) {
        // 当父组件数据变化时，确保子表数据同步
        if (newVal && Array.isArray(newVal)) {
          this.$emit('input', newVal);
        }
      },
      deep: true,
      immediate: true
    }
  },
  data() {
    return {
      currentRowIndex: -1,
      inventoryDialogVisible: false,
      selectedInventoryRow: null
    }
  },
  

  methods: {
    handleCurrentRowChange(currentRow) {
      this.currentRowIndex = this.value.indexOf(currentRow);
    },
    async openInventorySelector() {
      // 若未选中行但表有数据，则自动选中第一行
      if (this.currentRowIndex === undefined || this.currentRowIndex === null || this.currentRowIndex < 0) {
        if (Array.isArray(this.value) && this.value.length > 0) {
          this.currentRowIndex = 0;
          this.$nextTick(() => {
            if (this.$refs.detailTable && this.value[0]) {
              this.$refs.detailTable.setCurrentRow(this.value[0]);
            }
          });
        } else {
          this.$message.warning('请先新增一行明细');
          return;
        }
      }
      // 尝试自动查询：materialId → materialCode → materialName（模糊）
      const target = this.value[this.currentRowIndex];
      const tryQueries = [];
      if (target && target.materialCode) {
        // 后端支持 material.materialCode
        tryQueries.push({ key: 'material.materialCode', val: target.materialCode });
      }
      if (target && target.materialId) {
        tryQueries.push({ key: 'materialId', val: target.materialId });
      }
      if (target && target.materialName) {
        tryQueries.push({ key: 'material.materialName', val: target.materialName });
      }

      const pickBest = (rows) => {
        if (!rows || !rows.length) return null;
        // 仅考虑状态=正常的库存
        let candidates = rows.filter(r => String(r.status) === '1');
        if (!candidates.length) candidates = rows;
        // 若目标行带有批号，优先匹配相同批号
        if (target && target.batchNumber) {
          const sameBatch = candidates.find(r => String(r.batchNo || '') === String(target.batchNumber));
          if (sameBatch) return sameBatch;
        }
        // 默认选择数量最大的记录，避免随机性
        candidates.sort((a, b) => Number(b.quantity || 0) - Number(a.quantity || 0));
        return candidates[0];
      };

      try {
        for (const q of tryQueries) {
          const params = { pageNum: 1, pageSize: 50, status: 1 };
          params[q.key] = q.val;
          const res = await listInventory(params);
          const best = pickBest(res && res.rows);
          if (best) {
            const warehouseName = (best.warehouse && best.warehouse.name) || '';
            const qty = Number(best.quantity) || 0;
            const inventoryId = best.id;
            const warehouseId = (best.warehouse && best.warehouse.id) || null;
            const areaId = (best.storageArea && best.storageArea.id) || null;
            const unit = best.unit || '';
            const batchNo = best.batchNo || '';
            target.warehouse = warehouseName;
            target.stockQuantity = qty;
            target.inventoryId = inventoryId;
            target.warehouseId = warehouseId;
            target.areaId = areaId;
            target.unit = unit || target.unit;
            target.batchNumber = batchNo || target.batchNumber;
            this.$emit('input', this.value);
            this.$message.success(`已自动获取库存：${warehouseName}（库存 ${qty}）`);
            return; // 命中则不弹窗
          }
        }
        // 兜底：若以上条件均未命中，尝试按物料名称做前端过滤
        if (target && target.materialName) {
          const res = await listInventory({ pageNum: 1, pageSize: 9999, status: 1 });
          const rows = (res && res.rows) || [];
          const kw = String(target.materialName).toLowerCase();
          const filtered = rows.filter(r => {
            const name = r && r.material && r.material.materialName ? String(r.material.materialName).toLowerCase() : '';
            return name.includes(kw);
          });
          const best = pickBest(filtered);
          if (best) {
            const warehouseName = (best.warehouse && best.warehouse.name) || '';
            const qty = Number(best.quantity) || 0;
            const inventoryId = best.id;
            const warehouseId = (best.warehouse && best.warehouse.id) || null;
            const areaId = (best.storageArea && best.storageArea.id) || null;
            const unit = best.unit || '';
            const batchNo = best.batchNo || '';
            target.warehouse = warehouseName;
            target.stockQuantity = qty;
            target.inventoryId = inventoryId;
            target.warehouseId = warehouseId;
            target.areaId = areaId;
            target.unit = unit || target.unit;
            target.batchNumber = batchNo || target.batchNumber;
            this.$emit('input', this.value);
            this.$message.success(`已自动获取库存：${warehouseName}（库存 ${qty}）`);
            return;
          }
        }
      } catch (e) {
        console.error('自动获取库存失败', e);
      }
      // 兜底：打开选择弹窗手动选择
      this.selectedInventoryRow = null;
      this.inventoryDialogVisible = true;
    },
    onInventoryRowClick(row) {
      this.selectedInventoryRow = row;
      // 选择后立即显示提示信息
      if (row) {
        this.$message.success(`已选择：${row.material && row.material.materialName || '未知物料'} - ${row.warehouse && row.warehouse.name || '未知仓库'}`);
      }
    },
    applySelectedInventory() {
      if (!this.selectedInventoryRow) {
        this.$message.warning('请在弹窗中选择一条库存');
        return;
      }
      
      const target = this.value[this.currentRowIndex];
      if (!target) {
        this.$message.error('未找到目标行');
        return;
      }
      
      try {
        // 提取库存信息
        const warehouseName = (this.selectedInventoryRow.warehouse && this.selectedInventoryRow.warehouse.name) || '';
        const qty = Number(this.selectedInventoryRow.quantity) || 0;
        const inventoryId = this.selectedInventoryRow.id;
        const warehouseId = (this.selectedInventoryRow.warehouse && this.selectedInventoryRow.warehouse.id) || null;
        const areaId = (this.selectedInventoryRow.storageArea && this.selectedInventoryRow.storageArea.id) || null;
        const unit = this.selectedInventoryRow.unit || '';
        const batchNo = this.selectedInventoryRow.batchNo || '';
        
        // 验证必要信息
        if (!warehouseName) {
          this.$message.error('所选库存缺少仓库信息');
          return;
        }
        
        if (!inventoryId) {
          this.$message.error('所选库存缺少库存ID信息');
          return;
        }
        
        // 回填数据
        target.warehouse = warehouseName;
        target.stockQuantity = qty;
        target.inventoryId = inventoryId;
        target.warehouseId = warehouseId;
        target.areaId = areaId;
        target.unit = unit || target.unit;
        target.batchNumber = batchNo || target.batchNumber;
        
        // 触发数据更新
        this.$emit('input', this.value);
        
        // 关闭弹窗并显示成功信息
        this.inventoryDialogVisible = false;
        this.$message.success(`已成功回填库存信息：${warehouseName} - 库存数量：${qty}`);
        
        // 清空选择状态
        this.selectedInventoryRow = null;
        
      } catch (error) {
        console.error('回填库存信息失败:', error);
        this.$message.error('回填库存信息失败，请重试');
      }
    },
    /** 添加新行 */
    handleAddRow() {
      const newRow = {
        id: null,
        materialCode: '',
        materialName: '',
        materialSpec: '标准规格',
        unit: '个',
        attribute: '生产物料',
        batchNumber: `BATCH-${Date.now()}`,
        warehouse: '',
        location: 'A-01-01',
        requiredQuantity: 0,
        actualQuantity: 0,
        stockQuantity: 0,
        sourceDocument: '',
        sourceOrder: '',
        remark: '',
        createTime: null,
        updateTime: null,
        parentId: null
      };
      this.value.push(newRow);
      this.$emit('input', this.value);
      
    },
    
    /** 修改行 */
    handleEdit(row, index) {
      // 这里可以打开编辑对话框或者切换到编辑模式
      this.$message.success(`修改第${index + 1}行数据`);
      // 可以触发一个事件让父组件处理编辑逻辑
      this.$emit('edit', { row, index });
    },
    /** 删除行 */
    handleDelete(index) {
      this.$confirm('确认删除这条记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.value.splice(index, 1);
        this.$emit('input', this.value);
        this.$message.success('删除成功');
      }).catch(() => {});
    },
    
    /** 更新实发数量 */
    updateActualQuantity(quantity) {
      if (this.value && this.value.length > 0) {
        this.value.forEach(detail => {
          detail.actualQuantity = quantity || 0;
        });
        this.$emit('input', this.value);
      }
    },
    
    /** 更新需求数量 */
    updateRequiredQuantity(quantity) {
      if (this.value && this.value.length > 0) {
        this.value.forEach(detail => {
          detail.requiredQuantity = quantity || 0;
        });
        this.$emit('input', this.value);
      }
    },
    
    /** 判断库存是否不足 */
    isInsufficientStock(row) {
      if (!row.stockQuantity || !row.requiredQuantity) {
        return false;
      }
      
      // 计算可用库存（当前库存 - 锁定库存）
      const availableStock = Number(row.stockQuantity) - Number(row.lockedQuantity || 0);
      const requiredQty = Number(row.requiredQuantity);
      
      return requiredQty > availableStock;
    },
    
    /** 刷新库存列表 */
    refreshInventoryList() {
      if (this.$refs.inventoryRef) {
        // 调用子组件的刷新方法
        if (this.$refs.inventoryRef.getList) {
          this.$refs.inventoryRef.getList();
        }
        // 清空当前选择
        this.selectedInventoryRow = null;
        this.$message.success('库存列表已刷新');
      }
    },
    
    /** 显示选择说明 */
    showSelectionHelp() {
      this.$alert(`
        <div style="text-align: left;">
          <h4>库存选择说明：</h4>
          <ol>
            <li><strong>选择库存行：</strong>点击上方表格中的任意一行来选择库存</li>
            <li><strong>确认选择：</strong>选择后会显示已选择的库存信息</li>
            <li><strong>刷新列表：</strong>如果数据不准确，可以点击"刷新库存列表"按钮</li>
            <li><strong>应用选择：</strong>确认无误后点击"确定"按钮应用选择</li>
          </ol>
          <p style="color: #e6a23c; margin-top: 10px;">
            <i class="el-icon-warning"></i> 注意：选择库存后，系统会自动回填仓库、库位、库存数量等信息
          </p>
        </div>
      `, '选择说明', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '我知道了'
      });
    },
    
    /** 调试选择状态 */
    debugSelectionState() {
      const debugInfo = {
        '当前行索引': this.currentRowIndex,
        '已选择库存': this.selectedInventoryRow ? '是' : '否',
        '选择状态': this.selectedInventoryRow ? '已选择' : '未选择',
        '目标行数据': this.currentRowIndex >= 0 ? this.value[this.currentRowIndex] : '无',
        '库存弹窗状态': this.inventoryDialogVisible ? '已打开' : '已关闭'
      };
      
      if (this.selectedInventoryRow) {
        debugInfo['选中库存详情'] = {
          '库存ID': this.selectedInventoryRow.id,
          '物料名称': this.selectedInventoryRow.material && this.selectedInventoryRow.material.materialName,
          '仓库名称': this.selectedInventoryRow.warehouse && this.selectedInventoryRow.warehouse.name,
          '库存数量': this.selectedInventoryRow.quantity
        };
      }
      
      console.log('调试信息:', debugInfo);
      
      this.$alert(`
        <div style="text-align: left;">
          <h4>当前选择状态：</h4>
          <ul>
            <li><strong>当前行索引：</strong>${debugInfo['当前行索引']}</li>
            <li><strong>选择状态：</strong>${debugInfo['选择状态']}</li>
            <li><strong>弹窗状态：</strong>${debugInfo['库存弹窗状态']}</li>
          </ul>
          ${this.selectedInventoryRow ? `
          <h4>已选择库存信息：</h4>
          <ul>
            <li><strong>库存ID：</strong>${debugInfo['选中库存详情']['库存ID']}</li>
            <li><strong>物料名称：</strong>${debugInfo['选中库存详情']['物料名称'] || '未知'}</li>
            <li><strong>仓库名称：</strong>${debugInfo['选中库存详情']['仓库名称'] || '未知'}</li>
            <li><strong>库存数量：</strong>${debugInfo['选中库存详情']['库存数量'] || 0}</li>
          </ul>
          ` : ''}
          <p style="color: #409eff; margin-top: 10px;">
            <i class="el-icon-info"></i> 详细调试信息已输出到浏览器控制台
          </p>
        </div>
      `, '调试信息', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: '关闭'
      });
    }
  }
}
</script>

<style scoped>
.insufficient-stock {
  color: #f56c6c;
  font-weight: bold;
}

.el-tag--danger {
  margin-left: 5px;
}
</style> 